<template>
  <view class="poster-popup">
    <view v-if="!stillShow || shareImg" class="poster-popup-layer" :class="{ in: showPop, zIndex: showZindex }" @touchmove.stop="() => {}" @click.stop.prevent="close"></view>
    <view v-if="shareImg && showZindex" class="share-image" @click="close">
      <image :src="shareImg" class="img" />
      <view class="share-save-btn">长按图片保存</view>
    </view>
    <view v-else>
      <view class="poster-swiper-container" :class="{ in: showPop, zIndex: showZindex, 'poster-swiper-commodity': posterType === 'commodity' }" @touchmove.stop="() => {}">
        <swiper class="swiper-container" previous-margin="85rpx" next-margin="85rpx" @change="change">
          <swiper-item v-for="(item, index) in shareData" :key="index">
            <view class="swiper-item" :class="{ active: currentIndex === index }">
              <view class="product-info">
                <view class="product-info-pic">
                  <b-image v-if="item.pic" :src="item.pic" />
                </view>
                <view class="product-info-wrapper">
                  <view class="product-info-detail">
                    <view v-if="posterType === 'commodity'" class="product-info-tip"><image src="/static/images/share/icon_share_juhui.png" /></view>
                    <view v-if="posterType === 'commodity'" class="product-info-price">
                      <text>{{ _formatMoney(item.price) }}</text>
                      <text>￥{{ _formatMoney(item.original) }}</text>
                    </view>

                    <view v-if="item.titleArr" class="product-info-title">
                      <view v-for="(t, k) in item.titleArr" :key="k">{{ t }}</view>
                    </view>
                    <view v-else class="product-info-title">
                      <view v-if="item.platform" class="platform-text" :class="'platform-' + item.platform">{{ item.platform === 'PDD' ? '拼多多' : '唯品会' }}</view>
                      {{ item.title }}
                    </view>
                    <view class="user-info">
                      <view v-if="user.head_img" class="user-avatar"><b-image :src="user.head_img" /></view>
                      <view v-else class="user-avatar"><b-image src="/static/images/mine/touxiang.png" /></view>
                      <view class="user-nicname">
                        <text class="user-nicname-bot text-ellipsis-one">{{ user.nickname }}</text>
                        <!-- <text class="user-nicname-bot">好东西就要大家一起买</text> -->
                      </view>
                    </view>
                  </view>
                  <view v-if="item.codeUrl" class="product-info-code">
                    <image v-if="item.codeUrl" :src="item.codeUrl" />
                    <view>长按识别查看</view>
                  </view>
                </view>
                <view class="bg-bottom">
                  <!-- <image src="/static/images/share/share_foot.png" /> -->
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
      <view class="poster-popup-panel" :class="{ in: showPop, zIndex: showZindex }" @touchmove.stop="() => {}">
        <view class="poster-share-btn">
          <view v-if="shareTypes.includes(1)" class="share-item" @click="copyLink">
            <image src="/static/images/share/icon_share_01.png" class="share-icon-fixed" />
            <view class="share-txt">{{ shareOption.share_text ? '复制文案' : '复制链接' }}</view>
          </view>
          <view v-if="shareTypes.includes(2)" class="share-item relative-container" @click.stop.prevent="beforeShareImage('分享海报')">
            <image src="/static/images/share/icon_share_05.png" class="share-icon-fixed" />
            <view class="share-txt">分享海报</view>
          </view>
          <!-- #ifndef H5 -->
          <view v-if="shareTypes.includes(3)" class="share-item relative-container" @click.stop.prevent="beforeShareImage('微信好友')">
            <image src="/static/images/share/icon_share_04.png" class="share-icon-fixed" />
            <view class="share-txt">微信好友</view>
            <b-open-type open-type="share" :option="shareOption" @openTypeClick="close" />
          </view>
          <view v-if="shareTypes.includes(4)" class="share-item relative-container" @click.stop.prevent="beforeShareImage('朋友圈')">
            <image src="/static/images/share/icon_share_02.png" class="share-icon-fixed" />
            <view class="share-txt">朋友圈</view>
            <b-open-type open-type="share" :option="shareOption" />
          </view>
          <!-- #endif -->
          <view v-if="shareTypes.includes(5)" class="share-item" @click.stop.prevent="beforeShareImage('保存图文')">
            <image src="/static/images/share/icon_share_03.png" class="share-icon-fixed" />
            <view class="share-txt">保存图文</view>
          </view>
        </view>
        <view v-if="!stillShow" class="poster-share-cancel" @click.stop.prevent="close">取消</view>
      </view>
    </view>
    <view v-if="showQrCode" style="width:0;height:0;overflow:hidden;transform: translateX(-100%)">
      <tki-qrcode ref="qrcode" :val="codeVal" :size="400" :unit="'upx'" :show-loading="false" @result="getCodeUrl" />
    </view>
    <draw ref="drawImage" :rect="{ width: 750, height: 1334 }" />
    <!-- #ifdef MP-WEIXIN -->
    <confirm-popup ref="confirm"></confirm-popup>
    <!--  #endif -->
  </view>
</template>
<script>
import { formatMoney, setClipboardData } from '@/utils/tools'
import { mapGetters } from 'vuex'
import tkiQrcode from 'tki-qrcode'
import draw from '@/components/draw/index'
import { createSharePathUrl } from '@/utils/tools'
import store from '@/stores/index'
// #ifdef MP-WEIXIN
import confirmPopup from '@/components/confirmPopup/index'
// #endif
// #ifdef H5
// import save from 'save-file'
// #endif
export default {
  components: {
    tkiQrcode,
    draw,
    // #ifdef MP-WEIXIN
    confirmPopup
    // #endif
  },
  props: {
    shareOption: {
      type: Object,
      default() {
        // share_list: 海报内容
        // type: simple/whole
        return {}
      }
    },
    needH5: {
      type: Boolean, // 不显示小程序码 显示二维码
      default: false
    },
    stillShow: {
      type: Boolean,
      default: false
    },
    posterType: {
      type: String,
      default: ''
    },
    shareTypes: {
      type: Array,
      default() {
        return [5]
      }
    }
  },
  data() {
    return {
      showPop: false, // 做动画用
      showQrCode: false, // 是否展示H5二维码
      showZindex: false, // 做动画用
      timer: null,
      shareUrl: '', // 分享链接
      shareData: [], // 轮播数据
      currentIndex: 0,
      codeVal: '', // 二维码的值
      painting: {
        // 绘制图片的数据
        width: 750,
        height: 1334,
        views: []
      },
      shareImg: '',
      loading: false,
      option: {}
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.showQrCode = this.needH5
    // #ifdef H5
    this.showQrCode = true
    // #endif
    if (this.stillShow) {
      this.show()
    }
  },
  mounted() {},
  methods: {
    get_h5_url(share_url){
      let optionPath = share_url;
      if (optionPath) {
        if (optionPath.indexOf('isShare=') > 0) {
        } else if (optionPath.indexOf('?') > 0) {
          optionPath += `&isShare=true`
        } else {
          optionPath += `?isShare=true`
        }
      }
      if (store && store.state && store.state.userInfo && store.state.userInfo.invite_code) {
        if (optionPath) {
          if (optionPath.indexOf('?') > 0) {
            optionPath += `&share_code=${store.state.userInfo.invite_code}`
          } else {
            optionPath += `?share_code=${store.state.userInfo.invite_code}`
          }
        }
      }
      let path = process.env.VUE_APP_PRE_URL + `/pages/share/index?path=${encodeURIComponent(optionPath)}`
      return path
    },
    // 弹出
    async show(option = {}) {
      console.log('option', option)
      this.showZindex = true
      this.showPop = true
      this.shareImg = ''
      this.shareUrl = option.share_url 
      this.shareData = option.share_list 
      if (this.showQrCode) {
        // this.shareUrl = this.get_h5_url(this.shareUrl);
        this.shareUrl = createSharePathUrl({share_url: option.share_url},true);
        const urlObj = await this.$api.goodsApi.shortUrl({
          longurl: this.shareUrl
        })
        this.codeVal = urlObj.data || this.shareUrl
        setTimeout(() => {
          this.$refs.qrcode._makeCode()
        }, 200)
      } else {
        this.getWeinCode(option)
      }
    },
    // 小程序码获取
    async getWeinCode(option) {
			console.log(option.share_url);
      const path = createSharePathUrl({share_url: option.share_url})
      console.log(path)
      const res = await this.$api.commonApi.queryMiniCode({
        page: 'pages/share/index',
        scene: path,
        width: 430
      })
      if (res.success && res.data) {
        this.getCodeUrl(res.data.file_path)
      } else {
        this.getCodeUrl('')
      }
    },
    getCodeUrl(val) {
      if (!this.shareData || !this.shareData.length) {
        return
      }
      this.shareData = this.shareData.map(item => {
        item.codeUrl = val
        return item
      })
    },
    // 关闭
    close() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.stillShow) {
        this.shareImg = ''
        this.$emit('showChange', false)
      } else {
        this.showPop = false
        this.timer = setTimeout(() => {
          this.showZindex = false
          clearTimeout(this.timer)
        }, 300)
      }
    },
    change(e) {
      this.currentIndex = e.detail.current
    },
    // 复制链接
    copyLink() {
      this.$emit('btnClick', '复制链接')
      if (this.shareOption.share_text) {
        setClipboardData({
          data: this.shareOption.share_text,
          success: () => {
            uni.showToast({
              title: '文案已复制成功',
              icon: 'none',
              duration: 1500
            })
            this.close()
          }
        })
        return
      }
      let url = this.shareUrl
      if (!url.includes('http')) {
        url = `${process.env.VUE_APP_PRE_URL}${this.shareUrl}`
      }
      setClipboardData({
        data: url
      })
    },
    beforeShareImage(btnText) {
      this.$emit('btnClick', btnText)
      // #ifdef MP-WEIXIN
      uni.getSetting({
        success: res => {
          if (res.authSetting['scope.writePhotosAlbum'] !== undefined && !res.authSetting['scope.writePhotosAlbum']) {
            this.$refs.confirm.show({
              title: '提示',
              content: '保存到相册需要您的授权',
              yesTxt: '',
              yesCb: () => {},
              authBtn: true,
              openType: 'openSetting'
            })
          } else {
            this.createShareImage()
          }
        }
      })
      // #endif
      // #ifdef H5
      this.createShareImage()
      // #endif
    },
    // 生成分享图片
    createShareImage() {
      if (this.loading) return
      this.loading = true
      const currentData = this.shareData[this.currentIndex]
      if (currentData.minPrice) {
        currentData.price = currentData.minPrice
      }
      this.painting.views = []
      // 绘制背景
      this.pushArrRect('#ffffff', 0, 0, 750, 1200)
      this.pushArrImage('/static/images/share/share_foot.png', 1040, 0, 750, 160)
      if (this.user.head_img) {
        this.pushArrImage(this.toHttps(this.user.head_img), 1015, 40, 40, 40, [20, 20, 20, 20])
      } else {
        this.pushArrImage('/static/images/mine/touxiang.png', 1015, 40, 40, 40, [20, 20, 20, 20])
      }
      this.pushArrText(this.user.nickname || '', 1025, 100, '#bababa', 24, 411, 'left', 30, true, 1)
      // this.pushArrText('好东西就要大家一起买', 82, 146, '#999999', 24)
      this.pushArrImage(this.toHttps(currentData.pic), 15, 15, 720, 720, [0, 0, 0, 0])
      this.pushArrImage(currentData.codeUrl, 800, 522, 180, 180)
      this.pushArrText('长按识别查看', 1015, 547, '#666', 22)
      if (this.posterType === 'commodity') {
        const txtWidth = this.$refs.drawImage.getTextWidth('￥' + this._formatMoney(currentData.price), 70)
        this.pushArrImage('/static/images/share/icon_share_juhui.png', 745, 40, 135, 60)
        if (currentData.platform === 'PDD' || currentData.platform === 'VOP') {
          this.pushArrRect(currentData.platform === 'PDD' ? '#E42305' : '#E1017E', 914, 40, 88, 36)
          this.pushArrText(currentData.platform === 'PDD' ? '拼多多' : '唯品会', 921, 50, '#fff', 24)
          this.pushArrText(currentData.title.slice(0, 10), 920, 140, '#000000', 30, 300, 'left', 42, true, 1)
          this.pushArrText(currentData.title.slice(10, 100), 965, 40, '#000000', 30, 400, 'left', 42, true, 1)
        } else {
          this.pushArrText(currentData.title, 920, 40, '#000000', 30, 383, 'left', 42, true, 2)
        }

        this.pushArrText('￥', 840, 30, '#E11435', 40, 0, 'left', 50)
        this.pushArrText(this._formatMoney(currentData.price), 820, 60, '#E11435', 70, 0, 'left', 50)
        this.pushArrText('￥' + this._formatMoney(currentData.original), 840, 40 + txtWidth, '#999999', 30, 0, 'left', 38, false, 1, false, 'line-through')
      } else {
        if (currentData.titleArr) {
          currentData.titleArr.forEach((element, index) => {
            this.pushArrText(element, 806 + index * 48, 40, '#000000', 30, 383, 'left', 42, true, 3)
          })
        } else {
          this.pushArrText(currentData.title, 806, 40, '#000000', 30, 383, 'left', 42, true, 3)
        }
      }
      // const txtWidth = this.$refs.drawImage.getTextWidth('￥' + this._formatMoney(currentData.price), 48)
      // this.pushArrText('￥' + this._formatMoney(currentData.price), 1033, 62, '#F94640', 48, 0, 'left', 50)
      // if (!currentData.minPrice) {
      //   this.pushArrText('￥' + this._formatMoney(currentData.original), 1046, (62 + txtWidth + 20), '#999999', 30, 0, 'left', 38, false, 1, false, 'line-through')
      // }
      // if (this.allData.full_cut_id) {
      //   this.pushArrText('满减', 972, 62, '#ffffff', 20, 50, 'left', 30, false, 1, false, 'background', { color: '#e21536', top: 970, left: 60, width: 50, height: 22 })
      // } else {
      //   this.pushArrImage('/static/images/share/icon_share_juhui.png', 972, 62, 99, 33)
      // }
      // this.pushArrImage('/static/images/share/share_foot.png', 1175, 0, 750, 159)
      uni.showLoading({
        title: '海报生成中...'
      })
      setTimeout(() => {
        this.$refs.drawImage.beginDraw(this.painting, url => {
          uni.hideLoading()
          this.loading = false
          if (!url) {
            this.$gc.toast('保存失败')
            return
          }

          // #ifdef MP-WEIXIN
          uni.saveImageToPhotosAlbum({
            filePath: url,
            success: () => {
              this.$gc.toast('保存成功')
              this.close()
            }
          })
          // #endif
          // #ifdef H5
          this.shareImg = url
          this.$emit('showChange', true)
          // save(url, currentData.title + '.png')
          // #endif
        })
      }, 500)
      setTimeout(() => {
        if (this.loading) {
          uni.hideLoading()
        }
      }, 8000)
    },
    // 生成图片数据拼凑
    pushArrImage(url, top, left, width, height, border = [], type = 1) {
      this.painting.views.push({
        style: 'image',
        url: url,
        top: top,
        left: left,
        width: width,
        height: height,
        border: border,
        type: type
      })
    },
    pushArrRect(background, top, left, width, height, type = 1) {
      this.painting.views.push({
        style: 'rect',
        background: background,
        top: top,
        left: left,
        width: width,
        height: height,
        type: type
      })
    },
    pushArrText(content, top, left, color, fontSize = 22, width = 0, textAlign = 'left', lineHeight = 30, breakWord = false, MaxLineNumber = 1, bolder = false, textDecoration = 'none', bg = {}) {
      this.painting.views.push({
        style: 'text',
        content: content, // 绘制文本
        color: color, // 颜色
        fontSize: fontSize, // 字体大小
        textAlign: textAlign, // 文字对齐方式
        lineHeight: lineHeight, // 多行文本中才能使用
        top: top, // 文本左上角距离画板顶部的距离
        left: left, // 文本左上角距离画板左侧的距离
        width: width, // 和 MaxLineNumber 属性配套使用，width 就是达到换行的宽度
        breakWord: breakWord, // 是否需要换行
        MaxLineNumber: MaxLineNumber, // 最大行数，只有设置 breakWord: true
        bolder: bolder, // 是否加粗
        textDecoration: textDecoration, // 显示中划线、下划线效果 underline（下划线）、line-through（中划线)
        bg: bg
      })
    },
    _formatMoney(price) {
      if (typeof price === undefined || price === '') {
        return 0.0
      }
      return formatMoney(price)
    },
    toHttps(src) {
      if (src.indexOf('https') === -1) {
        let newSrc = src
        if (src.indexOf('http') === 0) {
          newSrc = src.replace('http', 'https')
        }
        return newSrc
      } else {
        return src
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.poster-popup-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.2s;
  &.zIndex {
    z-index: 100;
  }
  &.in {
    opacity: 1;
  }
}
.poster-popup-panel {
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: -1;
  transform: translateY(100%);
  transition: transform 0.3s;
  padding-bottom: calc(constant(safe-area-inset-bottom));
  padding-bottom: calc(env(safe-area-inset-bottom));
  &.zIndex {
    z-index: 101;
  }
  &.in {
    transform: translateY(0);
  }
  .poster-panel-title {
    text-align: center;
    font-size: 34rpx;
    padding: 20rpx 0;
    .price {
      color: red;
    }
  }
  .poster-share-btn {
    display: flex;
    height: 250rpx;
    align-items: center;
    .share-item {
      flex: 1;
      text-align: center;
    }
    .share-txt {
      text-align: center;
      color: #333;
      font-size: 28rpx;
      padding-top: 10rpx;
    }
    .share-icon-fixed {
      width: 80rpx;
      height: 80rpx;
    }
  }
  .poster-share-cancel {
    text-align: center;
    font-size: 28rpx;
    padding: 20rpx 0;
    color: #333;
    background-color: #fafafa;
  }
}
.poster-swiper-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100%;
  display: flex;
  align-items: center;
  height: calc(100% - 316rpx);
  height: calc(100% - 316rpx - constant(safe-area-inset-bottom));
  height: calc(100% - 316rpx - env(safe-area-inset-bottom));
  opacity: 0;
  &.zIndex {
    z-index: 101;
  }
  &.in {
    opacity: 1;
  }
  &.poster-swiper-commodity {
    // height: 920rpx;
    .swiper-container {
      height: 920rpx;
    }
    .product-info {
      .product-info-wrapper {
        height: 240rpx;
      }
      .product-info-title {
        @include text-ellipsis-line(2);
      }
    }
  }
  .swiper-container {
    width: 100%;
    // height: 840rpx;
    height: 900rpx;
    .swiper-item {
      // height: 900rpx;
      width: 580rpx;
      height: 100%;
      background-image: url('~@/static/images/share/bg.png');
      background-size: 100% 100%;
      // background-color: #fff;
      transform: scale(0.9);
      transition: transform 0.3s;
      position: relative;
      &.active {
        transform: scale(1);
      }
    }
  }
  .user-info {
    display: flex;
    flex-direction: row;
    .user-avatar {
      width: 44rpx;
      height: 44rpx;
      border-radius: 33rpx;
      overflow: hidden;
    }
    .user-nicname {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding-left: 16rpx;
    }
    .user-nicname-top {
      font-size: 18rpx;
      color: #000;
      line-height: 26rpx;
      width: 411rpx;
    }
    .user-nicname-bot {
      font-size: 18rpx;
      color: #999;
      line-height: 22rpx;
    }
  }
  .product-info {
    width: 100%;
    box-sizing: border-box;
    padding: 12rpx 12rpx 0 12rpx;
    .product-info-wrapper {
      display: flex;
      box-sizing: border-box;
      height: 220rpx;
      padding: 30rpx 25rpx 0rpx 20rpx;
      // border-bottom-left-radius: 20rpx;
      // border-bottom-right-radius: 20rpx;
      justify-content: space-between;
      // box-shadow: 0 10rpx 10rpx rgba(0,0,0,0.1);
    }
    .product-info-detail {
      display: flex;
      justify-content: space-between;
      flex-direction: column;
    }
    .product-info-pic {
      width: 556rpx;
      height: 556rpx;
      display: block;
      // border-top-left-radius: 22rpx;
      // border-top-right-radius: 22rpx;
      overflow: hidden;
      image {
        width: 100%;
        height: 100%;
        display: block;
      }
    }
    .product-info-title {
      font-size: 24rpx;
      line-height: 32rpx;
      width: 337rpx;
      color: #000;
      @include text-ellipsis-line(3);
      .platform-text {
        color: #fff;
        font-size: 20rpx;
        padding: 0 4rpx;
        line-height: 28rpx;
        background: #e42305;
        display: inline-block;
        vertical-align: middle;
        border-radius: 6rpx;
        margin-bottom: 8rpx;
        margin-right: 8rpx;
        &.platform-VOP {
          background: #e1017e;
        }
      }
    }
    .product-info-tip {
      width: 98rpx;
      height: 44rpx;
      display: block;
      margin-top: -20rpx;
      image {
        width: 98rpx;
        height: 44rpx;
        display: block;
      }
    }
    .product-info-price {
      text:nth-child(1) {
        font-size: 50rpx;
        color: #e11435;
        &::before {
          font-size: 26rpx;
          content: '￥';
        }
      }
      text:nth-child(2) {
        font-size: 20rpx;
        color: #999;
        text-decoration: line-through;
        padding-left: 12rpx;
        line-height: 22rpx;
      }
    }
    .product-info-code {
      width: 117rpx;
      image {
        width: 117rpx;
        height: 117rpx;
        display: block;
        padding-top: 6rpx;
      }
      view {
        width: 100%;
        font-size: 16rpx;
        color: #999;
        word-break: keep-all;
        padding-top: 20rpx;
        text-align: center;
      }
    }
  }
  .bg-bottom {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    image {
      width: 550rpx;
      height: 116rpx;
      display: block;
    }
  }
  .full-cut-icon {
    background: rgba(226, 21, 54, 1);
    border-radius: 5rpx;
    width: 50rpx;
    height: 30rpx;
    font-size: 20rpx;
    line-height: 30rpx;
    text-align: center;
    color: rgba(255, 255, 255, 1);
    margin: 10rpx 0 10rpx 4rpx;
  }
}
.share-image {
  width: 600rpx;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 101;
  min-height: 900rpx;
  .img {
    width: 600rpx;
    height: 1067rpx;
  }
  .share-save-btn {
    color: #fff;
    text-align: center;
    font-size: 28rpx;
    padding: 30rpx 0;
    width: 300rpx;
    position: absolute;
    bottom: -30rpx;
    left: 50%;
    margin-left: -150rpx;
  }
}
</style>
